// pages/me/me.js
const util = require("../../utils/util")
const majors = {
  "保密":['保密'],
  "经济学": ["国际经济与贸易", "金融工程", "数字经济"],
  "法学": ["法学", "知识产权"],
  "教育学": ["学前教育", "教育技术学", "体育教育", "社会体育指导与管理", "应用心理学"],
  "文学": ["汉语言文学", "汉语国际教育", "英语", "日语", "商务英语", "网络与新媒体"],
  "理学": [
    "数学与应用数学", "物理学", "应用物理学", "化学", "应用化学", 
    "地理科学", "地理信息科学", "生物科学", "统计学"
  ],
  "工学": [
    "机械设计制造及其自动化", "车辆工程", "智能制造工程", "材料成型及控制工程",
    "焊接技术与工程", "复合材料与工程", "电子信息工程", "微电子科学与工程",
    "人工智能", "自动化", "计算机科学与技术", "软件工程", "网络工程",
    "物联网工程", "数据科学与大数据技术", "土木工程", "化学工程与工艺",
    "环境工程", "环境生态工程", "资源环境科学", "食品质量与安全",
    "城乡规划", "建筑学", "风景园林", "工程造价"
  ],
  "医学": [
    "临床医学", "口腔医学", "预防医学", "护理学", "药学", "生物制药",
    "医学检验技术", "康复治疗学"
  ],
  "管理学": [
    "会计学", "审计学", "工商管理", "市场营销", "物流管理", "旅游管理",
    "酒店管理", "跨境电子商务"
  ],
  "艺术学": [
    "音乐学", "舞蹈学", "美术学", "绘画", "视觉传达设计", "环境设计", "产品设计"
  ]
};

// 工具函数 - 写在页面 JS 文件顶部或 utils 工具类中
function formatTime(postTimeStr) {
  // 处理 iOS/Safari 兼容性问题
  const postDate = new Date(postTimeStr.replace(' ', 'T'));
  const now = new Date();
  const diff = now - postDate;

  // 未来时间直接返回完整格式
  if (diff < 0) return formatFullDate(postDate);

  const seconds = Math.floor(diff / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);

  if (seconds < 60) return `${seconds}秒前`;
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  return formatFullDate(postDate);
}

function formatFullDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return year !== new Date().getFullYear() 
    ? `${year}年${month}月${day}日` 
    : `${month}月${day}日`;
}

Page({
  data: {
    activeTab: 'dynamic',
    isLogin: wx.getStorageSync('isLogin') ? wx.getStorageSync('isLogin') : false,
    nickname:null,
    followers:0,
    follow:0,
    student_id:null,
    grade:null,
    major:null,
    majorname:null,
    username:null,
    avatar:"http://localhost:3527/images/avatar/avatar-default5.jpg",
    sex:null,
    timestamp: null,
    postsList: [],
    reviewList: [],
    comm_cnt:0,
    show:false,
  },
  onLoad(){
    this.loadData();
    // this.loadPosts();
    this.loadReview();
  },

  onShow() {
    console.log("onShow!!!!!!!!!!!!!!!!!!!!!!!!");
    this.loadData();
    console.log(this.data.avatar);
  },

  checkLogin() {
    let uid = wx.getStorageSync('uid')
    if (!uid){
      wx.navigateTo({
        url: '/pages/Login/Login',
        success: (res) => console.log('跳转成功',res),
        fail: (err) => console.error('跳转登录页失败', err)
      })
    } else{
      var that = this;
      wx.chooseMedia({
        count: 9,
        mediaType: ['image','video'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success(res) {
          var tempFilePaths = res.tempFiles[0].tempFilePath;
          console.log(res.tempFiles[0].tempFilePath)
          console.log(res.tempFiles[0].size)
          wx.uploadFile({
            filePath: tempFilePaths,
            name: 'file',
            header:{"Content-Type":"multipart/form-data"},
            url: 'http://127.0.0.1:3527/upfile',
            name: 'imgfile',
            formData:{
              dir: 'avatar',
            },
            success(uploadRes) {
              // 上传成功后的响应（后端返回的 JSON 数据）
              console.log("上传成功:", uploadRes.data);
              const result = JSON.parse(uploadRes.data);
              console.log("服务器返回:", result.data);
              let path = 'http://localhost:3527/images/avatar/'+result.data;
              wx.setStorageSync('avatar', path);
              that.setData({
                avatar:path+ '?t=' + Date.now(),
              });
              wx.request({
                url: 'http://localhost:3527/users/avatar',
                method: 'PUT',
                data: {"avatar":path,"user_id": wx.getStorageSync('uid') },
              })
            },
            fail(err) {
              console.error("上传失败:", err);
            }
          });
        }
      });
    }
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ activeTab: tab })
  },

  loadData(){
    this.setData({
      username : wx.getStorageSync('username'),
      followers : wx.getStorageSync('followers'),
      follow : wx.getStorageSync('follow'),
      grade : wx.getStorageSync('grade'),
      nickname : wx.getStorageSync('nickname'),
      student_id : wx.getStorageSync('student_id'),
      major:wx.getStorageSync('major'),
      sex:wx.getStorageSync('sex'),
      isLogin : wx.getStorageSync('isLogin'),
      category:wx.getStorageSync('category'),
      avatar : wx.getStorageSync('avatar') ? wx.getStorageSync('avatar') : this.data.avatar,
      timestamp: new Date().getTime(), // 新增时间戳
    })
    // majors[Object.keys(majors)[this.data.category]][this.data.major]
    let majorname = majors[Object.keys(majors)[this.data.category]][this.data.major];
    console.log("@@@@@@@@@@@@@@@@@@"+majorname);
    this.setData({
      majorname:majorname,
    })
  },

  loadReview(){
    let that = this;
    let uid = wx.getStorageSync('uid');
    console.log("*******");
    wx.request({
      url:'http://127.0.0.1:3527/reviews/findme/'+wx.getStorageSync('uid'),
      method:'GET',
      success(res){
        const processedList = res.data.data.map(item => {
          console.log(item);
          return {
            ...item, // 保留原始字段
            formatTime: formatTime(item.review_time) // 添加格式化时间字段
          };
        });
        that.setData({
          reviewList:processedList,
          comm_cnt:processedList.length
        })
      }
    })
  },

  // loadPosts() {
  //   let that = this;
  //   let uid = wx.getStorageSync('uid');
  //   console.log("*******");
  //   wx.request({
  //     url:'http://127.0.0.1:3527/posts/findall/'+wx.getStorageSync('uid'),
  //     method:'GET',
  //     success(res){
  //       const result = res.data.data;
  //       let list = that.data.postsList;
  //       result.forEach((item,index)=>{
  //         list.push(item); // 直接追加导致数据重复
  //       })
  //       that.setData({postsList:list})
  //     }
  //   })
  // },

  setting(event){
    wx.navigateTo({
      url: '/pages/settings/settings',
    })
  },

    // 跳转详情页
    toPostDetail(e) {
      let postId = e.currentTarget.dataset.postid;
      let uid = wx.getStorageSync('uid');
      wx.navigateTo({
        url: `/pages/detail/detail?pid=${postId}&uid=${uid}`,
        success: (res) => console.log('跳转成功',res),
        fail: (err) => console.error('跳转失败', err)
      })
    },

    onPullDownRefresh() {
      setTimeout(() => {
        wx.hideNavigationBarLoading();
        wx.hideLoading();
        wx.stopPullDownRefresh(); // 必须调用，否则页面会保持下拉状态
      }, 2000);
        wx.reLaunch({
          url: '/pages/me/me',
        })
    }
})